import { message } from "@/utils/message";
import type { AdaptiveConfig } from "@pureadmin/table";
import { delay } from "@pureadmin/utils";
import { h, onMounted, reactive, ref, toRaw } from "vue";
import axios from "axios";
import { addDialog } from "@/components/ReDialog";
import forms, { type FormProps } from "./form.vue";
import { insertUser, updateUser, deleteUser, seach } from "@/api/user";
export function useColumns() {
  const indexMethod = (index: number) => {
    return index + 1;
  };
  const formRef = ref();
  const form = reactive({
    nickname: "",
    phone: "",
    status: ""
  });
  const columns: TableColumnList = [
    {
      type: "selection",
      align: "left",
      reserveSelection: true
    },
    {
      type: "index",
      label: "用户编号",
      index: indexMethod,
      width: "100"
    },
    {
      label: "账号",
      prop: "username",
      width: "260"
    },
    {
      label: "头像",
      prop: "avatar",
      width: "100",
      slot: "avatar"
    },
    {
      label: "昵称",
      prop: "nickname",
      width: "260"
    },
    {
      label: "性别",
      prop: "sex",
      width: "200",
      cellRenderer: ({ row }) => (
        <>
          {row.sex == 1 ? (
            <el-tag effect="plain">男</el-tag>
          ) : (
            <el-tag effect="plain" type="danger">
              女
            </el-tag>
          )}
        </>
      )
    },
    {
      label: "邮箱",
      prop: "email",
      width: "260"
    },
    {
      label: "电话",
      prop: "phone",
      width: "260"
    },
    {
      label: "状态",
      prop: "status",
      width: "100",
      cellRenderer: ({ row }) => (
        <el-switch
          v-model={row.status}
          class="ml-2"
          active-value={1}
          inactive-value={0}
          inline-prompt
          active-text="启用"
          inactive-text="禁用"
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
        />
      )
    },
    {
      label: "所属部门",
      prop: "depName",
      width: "220"
    },
    {
      label: "创建时间",
      prop: "createTime",
      width: "260"
    },
    {
      label: "备注",
      prop: "remark",
      width: "220"
    },
    {
      label: "操作",
      fixed: "right",
      width: "150",
      slot: "operation"
    }
  ];
  const loading = ref(true);
  const dataList = ref([]);
  const pagination = reactive({
    pageSize: 10,
    currentPage: 1,
    pageSizes: [10, 15, 20],
    total: 0,
    align: "right",
    background: true,
    small: false
  });
  const loadingConfig = reactive({
    text: "正在加载第一页...",
    viewBox: "-10, -10, 50, 50",
    spinner: `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `
  });

  const adaptiveConfig: AdaptiveConfig = {
    /** 表格距离页面底部的偏移量，默认值为 `96` */
    offsetBottom: 96
    /** 是否固定表头，默认值为 `true`（如果不想固定表头，fixHeader设置为false并且表格要设置table-layout="auto"） */
    // fixHeader: true
    /** 页面 `resize` 时的防抖时间，默认值为 `60` ms */
    // timeout: 60
    /** 表头的 `z-index`，默认值为 `100` */
    // zIndex: 100
  };

  function onSizeChange(val) {
    pagination.pageSize = val;
    getPage();
  }

  function onCurrentChange(val) {
    loadingConfig.text = `加载中`;
    loading.value = true;
    delay(600).then(() => {
      loading.value = false;
    });
    pagination.currentPage = val;
    getPage();
  }

  function refresh() {
    loadingConfig.text = `正在刷新`;
    loading.value = true;
    getPage().then(() => {
      delay(600).then(() => {
        loading.value = false;
      });
    });
  }

  const handleEdit = (index: number, row) => {
    message(`您编辑了第 ${index} 行，数据为：${JSON.stringify(row)}`, {
      type: "success"
    });
  };

  const openLoding = (title = "新增", row?: any) => {
    addDialog({
      width: "50%",
      title: `${title}用户`,
      closeOnClickModal: false,
      draggable: true,
      contentRenderer: () => h(forms, { ref: formRef }),
      props: {
        // 赋默认值
        formInline: {
          title,
          nickname: row?.nickname ?? "",
          username: row?.username ?? "",
          password: row?.password ?? null,
          phone: row?.phone ?? null,
          email: row?.email ?? null,
          depId: row?.depId ?? 1,
          userId: row?.userId ?? "",
          sex: row?.sex ?? "1",
          status: row?.status ?? 1,
          remark: row?.remark ?? null
        }
      },
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormProps;

        FormRef.validate(async valid => {
          if (valid) {
            if (title === "新增") {
              const data = await insertUser(curData);
              if (data.code == 200) {
                message(data.msg, { type: "success" });
                getPage();
                setTimeout(() => {
                  done();
                }, 1000);
              } else {
                message(data.msg, { type: "error" });
              }
            } else {
              const data = await updateUser(curData);
              if (data.code == 200) {
                message(data.msg, { type: "success" });
                getPage();
                setTimeout(() => {
                  done();
                }, 1000);
              } else {
                message(data.msg, { type: "error" });
              }
            }
          } else {
            message("校验不通过,参数错误", { type: "error" });
          }
        });
      },
      beforeCancel: done => {
        message("您取消了操作");
        done();
      }
    });
  };

  const confirmEvent = async (index: number, row) => {
    const data = await deleteUser(row.userId);
    if (data.code == 200) {
      message(`您删除了第${index + 1}行的一条数据`, {
        type: "success"
      });
      delay(600).then(() => {
        getPage();
      });
    }
  };

  const cancelEvent = () => {
    message(`您取消了操作`);
  };

  const getPage = async () => {
    axios
      .get(
        `http://localhost:8182/User/page/${pagination.currentPage}/${pagination.pageSize}`
      )
      .then(res => {
        dataList.value = res.data.PageData.records;
        const page = res.data.PageData;
        pagination.total = page.totalRow;
      })
      .catch(error => {
        console.log(error);
      });
  };

  const search = async (form: any) => {
    const searchData = {
      nickname: form.nickname,
      phone: form.phone,
      status: form.status,
      pageNumber: pagination.currentPage,
      pageSize: pagination.pageSize
    };
    const { data } = await seach(toRaw(searchData));
    loadingConfig.text = "搜索中";
    loading.value = true;
    dataList.value = data.records;
    pagination.total = data.totalRow;
    setTimeout(() => {
      loading.value = false;
    }, 1000);
  };

  const reset = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    getPage();
  };

  onMounted(() => {
    delay(600).then(() => {
      loading.value = false;
      getPage();
    });
  });

  return {
    columns,
    pagination,
    loading,
    dataList,
    adaptiveConfig,
    loadingConfig,
    onSizeChange,
    onCurrentChange,
    handleEdit,
    confirmEvent,
    cancelEvent,
    form,
    openLoding,
    refresh,
    search,
    reset
  };
}
